package xin.nick.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xin.nick.config.SystemProperties;
import xin.nick.manager.CodingOpenManager;
import xin.nick.util.domain.MeResponse;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author Nick
 * @since 2023/3/22
 */
@Slf4j
@Controller
@RequestMapping("/api")
@RequiredArgsConstructor
public class LoginController {


    private final SystemProperties systemProperties;
    private final CodingOpenManager codingOpenManager;

    @GetMapping("/authorize")
    public void authorize(HttpServletResponse response) {

        try {
            // 构造授权链接
            String redirectUrl = codingOpenManager.getAuthorizeUrl();
            log.info("授权URL: " + redirectUrl);
            response.sendRedirect(redirectUrl);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 登录
     * @param code
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public String login(String code) {
        log.info("Coding开放平台登录,code为: " + code);
        Assert.isTrue(StrUtil.isNotBlank(code), "Invalid code");
        String accessToken = codingOpenManager.getAccessToken(code);
        MeResponse me = codingOpenManager.getMe(accessToken);
        log.info("me: {}" + me);
        return "欢迎: " + JSON.toJSONString(me);

    }

}
